package com.dqhl.community.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dqhl.community.R;
import com.dqhl.community.activity.CollectionActivity;
import com.dqhl.community.activity.LoginActivity;
import com.dqhl.community.activity.OrderActivity;
import com.dqhl.community.activity.PersonalInfoActivity;
import com.dqhl.community.activity.PersonalSettingActivity;
import com.dqhl.community.activity.RecordActivity;
import com.dqhl.community.activity.ShoppingCartActivity;
import com.dqhl.community.activity.WalletActivity;
import com.dqhl.community.base.BaseFragment;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.GetVersion;
import com.dqhl.community.view.CircleImageView;
import com.dqhl.community.view.SharePopupWindow;
import com.dqhl.community.view.WiperSwitch;
import com.mob.tools.utils.UIHandler;
import com.tencent.mm.sdk.openapi.IWXAPI;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by cheng on 2016/8/29.
 * 我的 fragment
 */
public class PersonalFragment extends BaseFragment implements View.OnClickListener,
        WiperSwitch.OnChangedListener, PlatformActionListener {

    private TextView tvTopTitle;
    private CircleImageView ivHeadPortrait; // 头像
    private TextView tvNickname; //用户昵称
    private TextView tvCommunityName; // 用户社区
    private String photoPath; // 头像的路径

    private TextView tvOrder; //订单
    private TextView tvRecord; //记录
    private TextView tvWallet; //钱包
    private TextView tvCollection; //收藏

    private LinearLayout llPersonalSetting; //个人设置
    private LinearLayout llRecommendFriends; // 推荐给好友
    private WiperSwitch switchMsgPush; // 消息推送开关
    private SharePopupWindow sharePopupWindow; //分享popupwindow
    private boolean isLogin;
    private LinearLayout ll_shoppingCart;//购物车
    private TextView mTvVersionName; //版本号

    //  微信分享参数
    private static final int MSG_TOAST = 6;
    private static final int MSG_ACTION_CCALLBACK = 7;
    private static final int MSG_CANCEL_NOTIFY = 8;
    private static String Wx_login = null;
    // IWX 是第三方app和微信通信的openapi接口
    private IWXAPI iwxapi;
    private Context mContext;
    private static String s_title = null, s_desc = null, s_link = null, s_imgurl = null;   //分享的参数
    /**
     * 1  是分享到朋友圈
     * <p>
     * 2 是分享到微信好友
     */
    private static int WXSignOne = 1;
    private static int WXSignTwo = 2;
    private static int Open = 0;
    private static int share_moment = 0;

    private String strNickname;
    private String strUserId;
    private String authentication;
//    private User user;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_personal, container, false);
        registerBroadcastReceiver();
        Dlog.e("GGPersonalFragment" + spUserInfo.getString(Constant.USER_INFO, ""));
//        Dlog.e("GGPersonalFragment" + user.toString());
        mContext = getActivity();
        //注册
//        iwxapi = WXAPIFactory.createWXAPI(this, APP_ID, true);
//        iwxapi.registerApp(APP_ID);
        initView(view);
        GetVersion.getVersion(mContext, mTvVersionName);
        initData();
        return view;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (user != null) {
//            strUserId = user.getUserid();
            strNickname = user.getNickname();
//            authentication = user.getAuthentication();
//            photoPath = user.getHead();
        }
        strUserId = spUserInfo.getString(Constant.USERID, "");
//        strNickname = spUserInfo.getString(Constant.NICKNAME, "");
        authentication = spUserInfo.getString(Constant.AUTHENTICATION, "");
        photoPath = spUserInfo.getString(Constant.PHOTO_PATH, "");
        Dlog.e("SharedPreferences里头像路径：" + photoPath);

        if (strUserId != null && strUserId.length() > 0) {
            isLogin = true;
            if (photoPath != null && photoPath.length() > 0) {
                ImageOptions imageOptions = new ImageOptions.Builder()
                        .setLoadingDrawableId(R.drawable.ic_no_head_portrait)
                        .setUseMemCache(true)
                        .setFailureDrawableId(R.drawable.ic_no_head_portrait)
                        .build();
                x.image().bind(ivHeadPortrait, Config.Api.img_url + photoPath, imageOptions);
            } else {
                // 显示一张默认的头像
                ivHeadPortrait.setImageResource(R.drawable.ic_no_head_portrait);
            }
            if (strNickname != null && strNickname.length() > 0) {
                tvNickname.setText(strNickname);
            } else {
                tvNickname.setText("修改昵称");
            }

            if (!"".equals(authentication) && authentication.length() > 0) {
                tvCommunityName.setText(spUserInfo.getString(Constant.COMMUNITY_ID, "未认证"));
//                tvCommunityName.setText(user.getCommunity_id());
            } else {
                tvCommunityName.setText("未认证");
            }
        } else {
            isLogin = false;
            ivHeadPortrait.setImageResource(R.drawable.ic_no_head_portrait);
            tvNickname.setText("未登录");
            tvCommunityName.setVisibility(View.GONE);
        }
    }

    /**
     * 定义 BroadcastReceiver
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.ACTION_PHOTO_MODIFY: // 更新头像
                    x.image().bind(ivHeadPortrait, intent.getStringExtra(Constant.PHOTO_PATH));
                    break;
                case Constant.ACTION_LOGOUT: //退出登录
                    isLogin = false;
                    strUserId = spUserInfo.getString(Constant.USERID, "");
                    strNickname = spUserInfo.getString(Constant.NICKNAME, "");
//                    strUserId = user.getUserid();
//                    strNickname = user.getNickname();
                    ivHeadPortrait.setImageResource(R.drawable.ic_no_head_portrait);
                    tvNickname.setText("未登录");
                    tvCommunityName.setVisibility(View.GONE);
                    break;
                case Constant.ACTION_LOGIN_SUCCESS: //登录成功
                    isLogin = true;
                    strUserId = spUserInfo.getString(Constant.USERID, "");
                    strNickname = spUserInfo.getString(Constant.NICKNAME, "");
                    authentication = spUserInfo.getString(Constant.AUTHENTICATION, "");
                    photoPath = spUserInfo.getString(Constant.PHOTO_PATH, "");
//                    strUserId = user.getUserid();
//                    strNickname = user.getNickname();
//                    authentication = user.getAuthentication();
//                    photoPath = user.getHead();
                    Dlog.e("authentication:" + authentication);
                    if (strNickname != null && strNickname.length() > 0) {
                        tvNickname.setText(strNickname);
                    } else {
                        tvNickname.setText("修改昵称");
                    }
                    tvCommunityName.setVisibility(View.VISIBLE);
                    if (!"".equals(authentication) && authentication.length() > 0) {
                        tvCommunityName.setText(spUserInfo.getString(Constant.COMMUNITY_ID, "未认证"));
//                        tvCommunityName.setText(user.getCommunity_id());listview item 弹出菜单
                    } else {
                        tvCommunityName.setText("未认证");
                    }
                    if (photoPath != null && photoPath.length() > 0) {
                        x.image().bind(ivHeadPortrait, Config.Api.img_url + photoPath);
                    } else {
                        // 显示一张默认的头像
                        ivHeadPortrait.setImageResource(R.drawable.ic_no_head_portrait);
                    }
                    break;
                case Constant.ACTION_UPDATA_SUCCESS://更换昵称成功
                    strNickname = spUserInfo.getString(Constant.NICKNAME, "");
//                    strNickname = user.getNickname();
                    tvNickname.setText(strNickname);
                    break;
                case Constant.ACTION_COMPLAIN: //认证成功
                    String communityName = intent.getStringExtra(Constant.COMMUNITY_NAME);
                    tvCommunityName.setText(communityName);
                    break;
            }
        }
    };

    /**
     * 注册广播
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_PHOTO_MODIFY);
        intentFilter.addAction(Constant.ACTION_LOGOUT);
        intentFilter.addAction(Constant.ACTION_COMPLAIN);
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_UPDATA_SUCCESS);
        getActivity().registerReceiver(receiver, intentFilter);
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view) {
        tvTopTitle = (TextView) view.findViewById(R.id.tv_top_title);
        tvTopTitle.setText(R.string.txt_title_personal);

        ivHeadPortrait = (CircleImageView) view.findViewById(R.id.iv_head_portrait);
        tvNickname = (TextView) view.findViewById(R.id.tv_nickname);
        tvCommunityName = (TextView) view.findViewById(R.id.tv_community_name);
        tvOrder = (TextView) view.findViewById(R.id.tv_order);
        tvRecord = (TextView) view.findViewById(R.id.tv_record);
        tvWallet = (TextView) view.findViewById(R.id.tv_wallet);
        tvCollection = (TextView) view.findViewById(R.id.tv_collection);
        llPersonalSetting = (LinearLayout) view.findViewById(R.id.ll_personal_setting);
        llRecommendFriends = (LinearLayout) view.findViewById(R.id.ll_recommend_friends);
        switchMsgPush = (WiperSwitch) view.findViewById(R.id.switch_msg_push);
        ll_shoppingCart = (LinearLayout) view.findViewById(R.id.ll_shoppingCart);
        mTvVersionName = (TextView) view.findViewById(R.id.tv_versionName);
        switchMsgPush.setChecked(false);

        ivHeadPortrait.setOnClickListener(this);
        tvNickname.setOnClickListener(this);
        tvOrder.setOnClickListener(this);
        tvRecord.setOnClickListener(this);
        tvWallet.setOnClickListener(this);
        tvCollection.setOnClickListener(this);
        llPersonalSetting.setOnClickListener(this);
        llRecommendFriends.setOnClickListener(this);
        switchMsgPush.setOnChangedListener(this);
        ll_shoppingCart.setOnClickListener(this);

        sharePopupWindow = new SharePopupWindow(this, itemsOnClick);
        // sharePopupWindow 消失的动画
        sharePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                sharePopupWindow.backgroundAlpha(1.0f);
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head_portrait:
            case R.id.tv_nickname:
                if (isLogin) {
                    overlay(PersonalInfoActivity.class);
                } else {
                    overlay(LoginActivity.class);
                }
                break;
            case R.id.tv_order: //跳到订单界面
                if (isLogin) {
                    if ("".equals(app.getAuthentication()) || app.getAuthentication() == null) {
                        toast(R.string.toast_go_to_auth);
                    } else {
                        overlay(OrderActivity.class);
                    }
                } else {
                    toast("请先登录");
                }
                break;
            case R.id.tv_record: //跳到记录界面
                if (isLogin) {
                    overlay(RecordActivity.class);
                } else {
                    toast("请先登录");
                }
                break;
            case R.id.tv_wallet: //跳到钱包界面
                if (isLogin) {
                    if ("".equals(app.getAuthentication()) || app.getAuthentication() == null) {
                        toast(R.string.toast_go_to_auth);
                    } else {
                        overlay(WalletActivity.class);
                    }
                } else {
                    toast("请先登录");
                }
                break;
            case R.id.tv_collection: //跳到收藏界面
                if (isLogin) {
                    if ("".equals(app.getAuthentication()) || app.getAuthentication() == null) {
                        toast(R.string.toast_go_to_auth);
                    } else {
                        overlay(CollectionActivity.class);
//                        overlay(EvaluateActivity.class);
                    }
                } else {
                    toast("请先登录");
                }
                break;
            case R.id.ll_personal_setting: //个人设置
                if (isLogin) {
                    overlay(PersonalSettingActivity.class);
                } else {
                    toast("请先登录");
                }
                break;
            case R.id.ll_recommend_friends: //推荐给好友
                sharePopupWindow.showAtLocation(this.getView(), Gravity.BOTTOM, 0, 0);
                sharePopupWindow.backgroundAlpha(0.5f);
                break;
            case R.id.ll_shoppingCart://购物车
                if (isLogin) {
                    overlay(ShoppingCartActivity.class);
                } else {
                    toast("请先登录");
                }
                break;
            default:
                break;
        }
    }

    View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_circle_of_friends:
                    toast("朋友圈");
                    showShare(1);
                    sharePopupWindow.dismiss();
                    break;
                case R.id.tv_weixin_friends:
                    toast("微信好友");
                    showShare(2);
                    sharePopupWindow.dismiss();
                    break;
                case R.id.tv_qq:
                    toast("QQ好友");
                    showShare(3);
                    sharePopupWindow.dismiss();
                    break;
                case R.id.iv_cancel:
                    sharePopupWindow.dismiss();
                    break;
                default:
                    sharePopupWindow.dismiss();
                    break;
            }
        }
    };

    /**
     * 消息推送开关的监听事件
     *
     * @param wiperSwitch
     * @param checkState
     */
    @Override
    public void OnChanged(WiperSwitch wiperSwitch, boolean checkState) {
        Dlog.e("checkState:" + checkState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销广播
        if (receiver != null) {
            getActivity().unregisterReceiver(receiver);
        }
    }

    //  分享
    private void showShare(int Ints) {
        if (Ints == 1) {
            //朋友圈
            Platform wechatmoments = ShareSDK.getPlatform(WechatMoments.NAME);
            WechatMoments.ShareParams oks = new WechatMoments.ShareParams();
            oks.setShareType(Platform.SHARE_WEBPAGE); // 分享到网页的方式打开连接
            oks.setText("智慧社区");
            oks.setTitle("智慧社区");
//            oks.setImageUrl(s_imgurl);
            Bitmap imageData = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            oks.setImageData(imageData);
            Dlog.e("GGs_link11 :" + s_link);
            oks.setUrl("http://www.wandoujia.com/apps/com.dqhl.community");
//            oks.setUrl(s_link.replace("/AGGH5", ""));
            //回调

            wechatmoments.setPlatformActionListener(this);
            wechatmoments.share(oks);

        } else if (Ints == 2) {
            //微信好友
            Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
            WechatMoments.ShareParams oks = new WechatMoments.ShareParams();
            oks.setShareType(Platform.SHARE_WEBPAGE); // 分享到网页的方式打开连接
//           oks.setText("智慧社区");
            oks.setTitle("智慧社区");
//            oks.setImageUrl(s_imgurl);
            Bitmap imageData = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            oks.setImageData(imageData);
            Dlog.e("GGs_link11 :" + s_link);
            oks.setUrl("http://www.wandoujia.com/apps/com.dqhl.community");

            //回调
            wechat.setPlatformActionListener(this);
            wechat.share(oks);
        } else {
            QQ.ShareParams qq = new QQ.ShareParams();
            qq.setTitle("智慧社区");
            qq.setTitleUrl("http://www.wandoujia.com/apps/com.dqhl.community");//分享后点击跳转链接
            qq.setText("智慧社区");
            qq.setImageUrl("http://img.wdjimg.com/mms/icon/v1/c/83/c8fb24d08eeadec76049408e377e083c_256_256.png");
            Platform qqq = ShareSDK.getPlatform(QQ.NAME);
            qqq.setPlatformActionListener(this);
            qqq.share(qq);
        }

    }

    @Override
    public void onCancel(Platform platform, int action) {
        // 取消
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, (Handler.Callback) mContext);
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        // TODO Auto-generated method stub
        // 成功
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, (Handler.Callback) mContext);
    }

    @Override
    public void onError(Platform arg0, int arg1, Throwable t) {
        // TODO Auto-generated method stub
        // 失敗
        //打印错误信息,print the error msg
        t.printStackTrace();
        //错误监听,handle the error msg
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = arg1;
        msg.obj = t;
        UIHandler.sendMessage(msg, (Handler.Callback) mContext);
        t.printStackTrace();
    }
}
